﻿<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>销售单管理</title>
    <script src="~/lib/vue/vue.global.min.js"></script>
    <script src="~/lib/element-plus/index.full.js"></script>
    <link href="~/lib/element-plus/index.min.css" rel="stylesheet" />
    <link href="~/lib/element-plus/index.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <style>
        /* 左侧菜单栏样式（新增） */
        #sidebar {
            width: 220px !important;
            min-width: 220px !important;
            max-width: 220px !important;
            flex-shrink: 0 !important;
            padding: 0;
            margin: 0;
        }

        /* 表格表头样式（新增） */
        .el-table__header th {
            background-color: #F5F5F5 !important; /* 表头背景色，可自定义 */
            color: #191919 !important; /* 表头文字颜色，可自定义 */
        }

        .container {
            width: 95%;
            height: 600px;
            margin: 20px auto;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .search-area {
            margin-bottom: 16px;
        }

        .btn-group {
            margin-bottom: 16px;
        }

        .custom-select,
        .el-input {
            width: 150px !important;
        }

        .el-table__fixed-column .cell {
            white-space: nowrap !important;
            overflow: hidden !important;
            text-overflow: ellipsis !important;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-form inline>
                <el-form-item label="销售单号">
                    <el-input v-model="Form.saleOrderNo" placeholder="请输入销售单号">
                    </el-input>
                </el-form-item>
                <el-form-item label="单据状态">
                    <el-select v-model="Form.orderStatus" placeholder="请选择" class="custom-select">
                        <el-option v-for="item in industryOptions" :key="item.dictValue"
                                   :label="item.dictLabel" :value="item.dictValue">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="客户名称">
                    <el-select v-model="Form.customerName" placeholder="请选择" class="custom-select">
                        <!-- 新增：全部选项 -->
                        <el-option label="全部" value=""></el-option>
                        <!-- 动态渲染后端返回的客户列表 -->
                        <el-option v-for="item in customerOptions"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="销售日期">
                    <el-date-picker v-model="Form.saleDate" type="date" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="loadData">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button v-on:click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 功能按钮区域 -->
        <div class="btn-group">
            <el-button type="primary" v-on:click="goToAddPage">新增</el-button>
            <el-button v-on:click="handleDelete">删除</el-button>
            <el-button>复制</el-button>
            <el-button type="primary" v-on:click ="handleBatchAudit" :disabled="selectedOrders.length === 0">审核</el-button>
            <el-button type="warning" v-on:click="handleBatchRevoke" :disabled="selectedOrders.length === 0">撤销</el-button>
            <el-button>关闭</el-button>
            <el-button>开启</el-button>
            <el-button>导出</el-button>
            <el-button>刷新</el-button>
        </div>

        <!-- 数据表格区域 -->
        <el-table :data="tableData" border style="width: 100%" ref="salesOrderTable" v-on:selection-change ="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="sales_order_id" label="销售订单id" width="120"></el-table-column>
            <el-table-column prop="sales_order_no" label="销售单号" fixed="left" width="150">
                <template #default="scope">
                    <span style="color: #409EFF; cursor: pointer;" v-on:click="gotoDetail(scope.row.sales_order_no)">
                        {{ scope.row.sales_order_no }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="document_status" label="单据状态" fixed="left" width="100">
                <template #default="scope">
                    {{ formatDocumentStatus(scope.row.document_status) }}
                </template>
            </el-table-column>
            <!-- 销售日期：年月日 -->
            <el-table-column prop="sales_date" label="销售日期" fixed="left" width="120">
                <template #default="scope">
                    {{ formatDate(scope.row.sales_date) }}
                </template>
            </el-table-column>
            <el-table-column prop="customer_name" label="客户名称" width="120"></el-table-column>
            <el-table-column prop="contact_person" label="联系人" width="100"></el-table-column>
            <el-table-column prop="contact_phone_number" label="联系方式" width="120"></el-table-column>
            <el-table-column prop="organization_name" label="销售部门" width="120"></el-table-column>
            <el-table-column prop="user_name1" label="销售负责人" width="120"></el-table-column>
            <el-table-column prop="prod_num" label="销售数量" width="100"></el-table-column>
            <el-table-column prop="saleamount" label="销售金额" width="100"></el-table-column>
            <el-table-column prop="product_name" label="销售货品" width="120"></el-table-column>
            <el-table-column prop="user_name" label="制单人" width="120"></el-table-column>
            <el-table-column prop="department" label="所在部门" width="120"></el-table-column>
            <!-- 制单时间：年月日 时分秒 -->
            <el-table-column prop="create_time" label="制单时间" width="180">
                <template #default="scope">
                    {{ formatDateTime(scope.row.create_time) }}
                </template>
            </el-table-column>
            <el-table-column prop="reviewer" label="审核人" width="120"></el-table-column>
            <el-table-column prop="review_time" label="审核时间" width="180">
                <template #default="scope">
                    {{ formatDateTime(scope.row.review_time) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
                <template #default="scope">
                    <!-- 当单据状态是未出库(6)或驳回(3)时，仅显示撤销按钮 -->
                    <el-button v-if="scope.row.document_status === '6' || scope.row.document_status === '3'"
                               type="text"
                               style="color: #409EFF;"
                    v-on:click ="handleSingleRevoke(scope.row.sales_order_id, scope.row)">
                        撤销
                    </el-button>
                    <!-- 其他状态时，显示编辑和删除按钮 -->
                    <template v-else>
                        <el-button-group>
                            <el-button type="text" v-on:click ="goToEdit(scope.row.sales_order_no)">编辑</el-button>
                            <el-button type="text" style="color: red; margin-left: 10px;" v-on:click ="handleSingleDelete(scope.row.sales_order_no, scope.row)">删除</el-button>
                        </el-button-group>
                    </template>
                </template>
            </el-table-column>
        </el-table>


        <!-- 审核模态框 -->
        <el-dialog v-model="auditDialogVisible" title="批量审核" width="450px">
           
                <el-radio-group v-model="auditForm.auditResult">
                    <el-radio label="1">通过</el-radio>
                    <el-radio label="0">驳回</el-radio>
                </el-radio-group>
                <el-form-item label="审核意见">
                <el-input v-model="auditForm.auditOpinion"
                          type="textarea"
                          :rows="4"  
                          placeholder="请输入审核意见"
                        ></el-input>
                </el-form-item>

            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click ="auditDialogVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click ="confirmBatchAudit">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 撤销确认框 -->
        <el-dialog v-model="revokeDialogVisible" title="提示" width="300px">
            <div style="text-align: center; margin-bottom: 20px;">
                <i class="el-icon-warning" style="color: #f90; font-size: 24px;"></i>
                <div style="margin-top: 10px;">是否撤销所选单据？</div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click ="revokeDialogVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click ="confirmBatchRevoke">确定</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 分页组件 -->
        <el-pagination v-on:size-change="handleSizeChange"
                       v-on:current-change="handleCurrentChange"
                       :current-page="pageIndex"
                       :page-sizes="[1, 2, 3, 4]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="totalCount"
                       style="margin-top: 16px;">
        </el-pagination>

    </div>

    <script>
        const { createApp, onMounted, reactive, ref } = Vue;
        const app = createApp({
            setup() {
               const tableData = ref([]);
            const totalCount = ref(0);
            const pageIndex = ref(1);
            const pageSize = ref(4);

            const Form = reactive({
                saleOrderNo: '',
                orderStatus: '',
                customerName: '',
                saleDate: null, // 注意：日期选择器绑定单个日期时用null
            });


                const handleSizeChange = (newSize) => {
                    pageSize.value = newSize;
                    loadData();

                };

                const handleCurrentChange = (newPage) => {
                    pageIndex.value = newPage;
                      loadData();

                };

               // 重置查询条件
            const resetSearch = () => {
                Form.saleOrderNo = '';
                Form.orderStatus = '';
                Form.customerName = '';
                Form.saleDate = null;
                pageIndex.value = 1;
                loadData();
            };


                    // 替换原日期转换逻辑
        const formatDateStr = (date) => {
          if (!date) return null;
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        };

                  // 加载数据（对接后端API）
            const loadData = async () => {
                try {
                           // 日期格式转换：将Date对象转为"YYYY-MM-DD"字符串
        const salesDateStr = Form.saleDate ? formatDateStr(Form.saleDate) : null;

                    const response = await axios.get('/SalesOrder/GetPagedSalesOrders', {
                        params: {
                            sales_order_no: Form.saleOrderNo,
                            document_status: Form.orderStatus,
                            customer_name: Form.customerName,
                            sales_date: salesDateStr, // 日期转字符串传递
                            currentPage: pageIndex.value,
                            pageSize: pageSize.value
                        }
                    });
                    tableData.value = response.data.data;
                    totalCount.value = response.data.total;
                    console.log('加载数据成功:', tableData.value);
                } catch (err) {
                    console.error('加载数据失败:', err);
                    ElementPlus.ElMessage.error('数据加载失败，请重试');
                }
            };

        // 仅显示年月日
        const formatDate = (dateStr) => {
          if (!dateStr) return '';
          const date = new Date(dateStr);
          return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
        };

        // 显示年月日 时分秒
        const formatDateTime = (dateStr) => {
          if (!dateStr) return '';
          const date = new Date(dateStr);
          return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
        };


           const industryOptions = ref([]); //单据状态

              // 3. 获取后端字典数据单据状态
                const getIndustryDict = async () => {
                    try {

                        const response = await axios.get('/api/Dict/datas/StockOrderStatus');
                        console.log(response.data);
                        industryOptions.value = response.data || [];
                        console.log('获取单据状态成功:', industryOptions.value);
                    } catch (error) {
                        console.error('获取单据状态失败：', error);
                        ElementPlus.ElMessage.error('单据状态数据加载失败');
                    }
                };

             const customerOptions = ref([]);

               const getCustomerList = async () => {
            try {
                // 调用后端新增的客户列表接口
                const response = await axios.get('/SalesOrder/GetCustomerSelectList');
                customerOptions.value = response.data; // 绑定接口返回的客户数据
                console.log('获取客户列表成功:', customerOptions.value);
            } catch (err) {
                console.error('获取客户列表失败:', err);
                ElementPlus.ElMessage.error('客户数据加载失败');
            }
        };




                onMounted(() => {
                   loadData();
                 getIndustryDict();
                 getCustomerList();
                });

                const goToAddPage = () => {
                    window.location.href = '/SalesOrder/Add';
                };

                const gotoDetail = (saleOrderNo) => {
                    window.location.href = `/SalesOrder/SalesDetail?saleOrderNo=${saleOrderNo}`;
                };

                const goToEdit = (saleOrderNo) => {
                    window.location.href = `/SaleOrder/Edit?saleOrderNo=${saleOrderNo}`;
                };

                            // 单条逻辑删除
        const handleSingleDelete = (saleOrderNo, row) => {
            ElementPlus.ElMessageBox.confirm(
                '此操作将逻辑删除该销售单，是否继续？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(async () => {
                try {
                    // 在删除前清除该行的选中状态
                    if (salesOrderTable.value) {
                        salesOrderTable.value.toggleRowSelection(row, false);
                    }

                    // 显式设置Content-Type，并将参数转为JSON字符串
                    const response = await axios.post(
                        '/SalesOrder/LogicalDeleteSingle',
                        JSON.stringify(saleOrderNo), // 转为JSON字符串
                        {
                            headers: {
                                'Content-Type': 'application/json' // 指定请求格式
                            }
                        }
                    );
                    ElementPlus.ElMessage.success(response.data);
                    loadData();
                } catch (err) {
                    console.error('删除失败:', err);
                    ElementPlus.ElMessage.error(err.response?.data || '服务器异常');
                }
            }).catch(() => {
                ElementPlus.ElMessage.info('已取消删除');
            });
        };

                // 新增：表格ref
                const salesOrderTable = ref(null);

                      // 批量逻辑删除
        const handleDelete = () => {
            // 先判断表格ref是否已初始化
            if (!salesOrderTable.value) {
                ElementPlus.ElMessage.warning('表格未加载完成，请稍后再试');
                return;
            }

            // 使用 getSelectionRows() 方法获取选中行
            const selectedRows = salesOrderTable.value.getSelectionRows();

            if (selectedRows.length === 0) {
                ElementPlus.ElMessage.warning('请勾选需要删除的单据！');
                return;
            }

            const saleOrderNos = selectedRows.map(row => row.sales_order_no);
            ElementPlus.ElMessageBox.confirm(
                '此操作将逻辑删除选中的销售单，是否继续？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(async () => {
                try {
                    const response = await axios.post(
                        '/SalesOrder/LogicalDeleteBatch',
                        saleOrderNos,
                        {
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        }
                    );
                    ElementPlus.ElMessage.success(response.data);
                    loadData();
                } catch (err) {
                    console.error('批量删除失败:', err);
                    ElementPlus.ElMessage.error(err.response?.data || '服务器异常');
                }
            }).catch(() => {
                ElementPlus.ElMessage.info('已取消删除');
            });
        };

                        // 单据状态数字转中文
        const formatDocumentStatus = (status) => {
          const statusMap = {
            '1': '草稿',
            '2': '待审核',
            '3': '驳回',
            '6': '未出库',
            '7': '部分出库',
            '4': '已完成',
            '5': '未入库', // 匹配“全部”选项的空值
            '8': '部分入库'
          };
          return statusMap[status] || '未知状态';
        };



               // 选中的订单
        const selectedOrders = ref([]);
        // 审核弹窗
        const auditDialogVisible = ref(false);

              // 修改 auditForm 的初始化逻辑
        const auditForm = reactive({
          auditResult: '', // 字符串类型："1"代表通过，"0"代表驳回
          auditOpinion: ''
        });
        // 撤销弹窗
        const revokeDialogVisible = ref(false);

            // 选中订单变化
        const handleSelectionChange = (val) => {
          selectedOrders.value = val;
          console.log('选中的订单状态：', val.map(item => ({
            sales_order_id: item.sales_order_id,
            documentStatus: item.document_status
          })));
        };

             // 打开批量审核弹窗（校验状态）
        const handleBatchAudit = () => {
          const invalid = selectedOrders.value.some(item => item.document_status !== '2'); // 替换为后端实际的“待审核”值
          if (invalid) {
            ElementPlus.ElMessage.warning('请选择“待审核”的单据进行审核');
            return;
          }
          auditDialogVisible.value = true;
        };

                     const confirmBatchAudit = async () => {
          // 验证逻辑：直接访问 auditForm.auditResult 和 auditForm.auditOpinion
          if (auditForm.auditResult === '0' && !auditForm.auditOpinion) {
            ElementPlus.ElMessage.warning('驳回时请输入审核意见');
            return;
          }
          try {
                    // 1. 先打印 auditForm 的值（审核结果、审核意见）
        console.log('当前审核表单数据：', auditForm);

        // 2. 打印选中的订单 ID 列表
        const orderIds = selectedOrders.value.map(item => item.sales_order_id);
        console.log('选中的订单 ID 列表：', orderIds);

            const res = await axios.post('/SalesOrder/BatchAudit', {
              OrderIds: selectedOrders.value.map(item => item.sales_order_id),
              AuditResult: auditForm.auditResult, // 直接访问，无 .value
              AuditOpinion: auditForm.auditOpinion, // 直接访问，无 .value
              Reviewer: 'admin'
            });
            if (res.data>0) {
              ElementPlus.ElMessage.success('批量审核成功');
              auditDialogVisible.value = false;
              loadData();
            } else {
              ElementPlus.ElMessage.error(res.data.Message || '审核失败');
            }
          } catch (err) {
            ElementPlus.ElMessage.error('网络异常，请重试');
          }
        };

        // 打开批量撤销弹窗（校验状态）
        const handleBatchRevoke = () => {
            
          const invalid = selectedOrders.value.some(item =>
            item.document_status !== '6' && item.document_status !== '3'
          );
          if (invalid) {
            ElementPlus.ElMessage.warning('请选择“未出库”或“驳回”的单据进行撤销');
            return;
          }
          revokeDialogVisible.value = true;
        };

     
              // 确认批量撤销
        const confirmBatchRevoke = async () => {
          try {
            const res = await axios.post('/SalesOrder/BatchRevoke', {
              OrderIds: selectedOrders.value.map(item => item.sales_order_id)
            });
            if (res.data>0) {
              ElementPlus.ElMessage.success('批量撤销成功');
              revokeDialogVisible.value = false;
              loadData(); // 刷新列表
            } else {
              ElementPlus.ElMessage.error(res.data.Message || '撤销失败');
            }
          } catch (err) {
            ElementPlus.ElMessage.error('网络异常，请重试');
          }
        };


                // 单条撤销逻辑
        const handleSingleRevoke = (saleOrderId, row) => {
          ElementPlus.ElMessageBox.confirm(
            '此操作将撤销该单据，是否继续？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(async () => {
            try {
              // 调用后端单条撤销接口
              const response = await axios.post(
                '/SalesOrder/LogicalRevokeSingle',
                JSON.stringify(saleOrderId),
                {
                  headers: {
                    'Content-Type': 'application/json'
                  }
                }
              );
              ElementPlus.ElMessage.success(response.data);
              loadData(); // 刷新列表
            } catch (err) {
              console.error('单条撤销失败:', err);
              ElementPlus.ElMessage.error(err.response?.data || '服务器异常');
            }
          }).catch(() => {
            ElementPlus.ElMessage.info('已取消撤销');
          });
        };




                return {
                    tableData,
                    totalCount,
                    pageIndex,
                    pageSize,
                    loadData,
                    handleSizeChange,
                    handleCurrentChange,
                    resetSearch,
                    goToAddPage,
                    Form,
                    gotoDetail,
                    goToEdit,
                    handleSingleDelete,
                    handleDelete,
                    formatDate,
                    formatDateTime,
                    formatDocumentStatus,
                    industryOptions,
                    customerOptions,
                    formatDateStr,
                    salesOrderTable,

                    selectedOrders,
                    auditDialogVisible,
                    auditForm,
                    revokeDialogVisible,
                    handleSelectionChange,
                    handleBatchAudit,
                    confirmBatchAudit,
                    handleBatchRevoke,
                    confirmBatchRevoke,
                    handleSingleRevoke

                };
            }
        });
        app.use(ElementPlus);
        app.mount('.container');
    </script>
</body>

</html>